package com.jwdf.uda.ui.fragment.user;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.databinding.FragmentUserBinding;
import com.jwdf.uda.event.IndividualEvent;
import com.jwdf.uda.event.MessageNoticeEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.UpdateDeviceInfo;
import com.jwdf.uda.http.action.UserInfoAction;
import com.jwdf.uda.ui.activity.FansActivity;
import com.jwdf.uda.ui.activity.FeedbackActivity;
import com.jwdf.uda.ui.activity.FollowActivity;
import com.jwdf.uda.ui.activity.GarbActivity;
import com.jwdf.uda.ui.activity.MessageActivity;
import com.jwdf.uda.ui.activity.PhotoActivity;
import com.jwdf.uda.ui.activity.QuizMineActivity;
import com.jwdf.uda.ui.activity.SettingActivity;
import com.jwdf.uda.ui.activity.StylistGuideActivity;
import com.jwdf.uda.ui.activity.UserInfoActivity;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.DisplayUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.PromptUtil;
import com.jwdf.uda.utils.StringUtils;
import com.jwdf.uda.view.CircleImageView;
import com.jwdf.uda.view.prompt.UserPrompt;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.message.PushAgent;

import java.util.ArrayList;

import retrofit2.Response;

/**
 * Created by RD-001 on 2016/4/27.
 */
public class UserFragment extends BaseFragment {
    private FragmentUserBinding mBinding;
    private PbBean.PbUserInfo mUserInfo;

    public static UserFragment instance() {
        UserFragment view = new UserFragment();
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            loadUserInfo();
            if (PromptUtil.isShowUserPrompt(getActivity())) {
                new UserPrompt(getActivity(),mBinding.rlQuiz).show();
            }
        }
    }

    private void reportDeviceInfo(final Context context) {
        onNewRequestCall(UpdateDeviceInfo.newInstance(context, PushAgent.getInstance(context).getRegistrationId()).request(new AHttpService.IResCallback<PbBean.PbResSystemUpdateDeviceInfo>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResSystemUpdateDeviceInfo> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (response != null) {
                    if (HttpHelper.showError(context, resultCode, baseServerInfo, getString(R.string.error_net))) {
                    }
                    PbBean.PbResSystemUpdateDeviceInfo deviceInfo = response.body();
                    if (deviceInfo != null) {
                        ConfigUtils.setPageLength(context, deviceInfo.getPageLength());
                        ConfigUtils.setAboutPage(context, deviceInfo.getAboutPage());
                        ConfigUtils.setUserProtocol(context, deviceInfo.getUserProtocolPage());
                    }
                }
            }
        }));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mBinding = FragmentUserBinding.inflate(inflater, container, false);
        mBinding.setUserFragment(this);
        mBinding.userTitleLayout.setUserFragment(this);
        LinearLayout.LayoutParams flParams = (LinearLayout.LayoutParams) mBinding.userTitleLayout.getRoot().getLayoutParams();
        flParams.height += DisplayUtils.getStatusBarHeight(getContext());
        mBinding.userTitleLayout.getRoot().setLayoutParams(flParams);
        mBinding.userTitleLayout.titleMe.setPadding(0, DisplayUtils.getStatusBarHeight(getContext()), 0, 0);
        mBinding.userTitleLayout.flHeadAction.setPadding(DisplayUtils.dipToPix(getContext(),15), DisplayUtils.getStatusBarHeight(getContext()), DisplayUtils.dipToPix(getContext(),15), 0);
        loadUserInfo();
        return mBinding.getRoot();
    }

    private void loadUserInfo() {
        onNewRequestCall(UserInfoAction.newInstance(getContext()).request(new AHttpService.IResCallback<PbBean.PbResUserGetInfo>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserGetInfo> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_operation))) {
                        return;
                    }
                    reflashUserInfo(response.body());
                }
            }
        }));

    }

    private void reflashUserInfo(PbBean.PbResUserGetInfo body) {
        if (body != null) {
            PbBean.PbUserInfo userInfo = body.getUserInfo();
            mUserInfo = userInfo;
            mBinding.setIsDesigner(userInfo.getIsDesigner());
            mBinding.userAvatar.setTag(R.id.tag_url, userInfo.getAvatar().getUrl());
            ImageLoader.getInstance().displayImage(userInfo.getAvatar().getUrl(), mBinding.userAvatar);
            mBinding.ivDesigner.setVisibility(userInfo.getIsDesigner() ? View.VISIBLE : View.GONE);
            mBinding.userNickname.setText(StringUtils.filterNullAndTrim(userInfo.getNickname()));
            mBinding.userRealname.setVisibility(TextUtils.isEmpty(StringUtils.filterNullAndTrim(userInfo.getIntroduction())) ? View.GONE : View.VISIBLE);
            mBinding.userRealname.setText(userInfo.getIntroduction());
            mBinding.userFollow.setText(StringUtils.filterNullAndTrim(String.valueOf(userInfo.getFollowCount())));
            mBinding.llFollows.setTag(R.id.tag_follows, userInfo.getFollowCount());
            mBinding.userFans.setText(StringUtils.filterNullAndTrim(String.valueOf(userInfo.getFansCount())));
            mBinding.llFans.setTag(R.id.tag_fans, userInfo.getFansCount());
            mBinding.userMessageCount.setVisibility(userInfo.getMessageCount() > 0 ? View.VISIBLE : View.GONE);
            mBinding.userMessageCount.setText("" + userInfo.getMessageCount());

            reportDeviceInfo(getContext());

            EventBusUtil.post(new MessageNoticeEvent(MessageNoticeEvent.USER_TAB_TIPS, userInfo.getMessageCount()));

            ConfigUtils.setFollowCount(getActivity(), mUserInfo.getFollowCount());
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusUtil.registerEvent(this);
    }

    @Override
    public void onDestroy() {
        EventBusUtil.unregisterEvent(this);
        super.onDestroy();
    }

    public void onEvent(MessageNoticeEvent event) {
        if (MessageNoticeEvent.REFRESH_USER_INFO == event.getEvent()) {
            loadUserInfo();
        }
    }

    public void onEvent(IndividualEvent event) {
        loadUserInfo();
    }

    public void onUserInfoClick(View view) {
        if (mUserInfo != null) {
            UserInfoActivity.start(view.getContext(), mUserInfo.getUserId(), mUserInfo.getIsDesigner());
        }
    }

    public void onUserAvatarClick(View view) {
        CircleImageView imageView = (CircleImageView) view;
        final ArrayList<String> urls = new ArrayList<>();
        String avatarUrl = (String) imageView.getTag(R.id.tag_url);
        if (!TextUtils.isEmpty(avatarUrl)) {
            urls.add(avatarUrl);
            PhotoActivity.start(view.getContext(), urls, 0, 1, mUserInfo);
        }
    }

    public void onUserFollowClick(View view) {
        LinearLayout userFollows = (LinearLayout) view;
        Object value = userFollows.getTag(R.id.tag_follows);
        if (value != null && ((Integer) value).intValue() > 0) {
            startActivityFromFragment(FollowActivity.class);
        }
    }

    public void onUserFansClick(View view) {
        LinearLayout userFans = (LinearLayout) view;
        Object value = userFans.getTag(R.id.tag_fans);
        if (value != null && ((Integer) value).intValue() > 0) {
            startActivityFromFragment(FansActivity.class);
        }
    }

    public void onUserFeedback(View view) {
        startActivityFromFragment(FeedbackActivity.class);
    }

    public void onApplyDesigner(View view) {
        GarbActivity.start(getContext());
    }

    public void onApplyDesignerSty(View view) {
        StylistGuideActivity.startActivity(getContext());
    }

    //消息通知
    public void onUserMessageClick(View view) {
        startActivityFromFragment(MessageActivity.class);
    }

    //跳转设置界面
    public void onHeadActionClick(View view) {
        startActivityFromFragment(SettingActivity.class);
    }

    public void onUserQuizClick(View view) {
        QuizMineActivity.start(view.getContext());
    }

}
